package com.sm.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sm.domain.dto.LoginDTO;
import com.sm.domain.dto.Result;
import com.sm.domain.dto.UserDTO;
import com.sm.domain.po.User;
import com.sm.domain.vo.UserVo;
import com.sm.mapper.UserMapper;
import com.sm.service.UserService;
import com.sm.utils.JwtUtils;
import com.sm.utils.PermissionFeign;
import com.sm.utils.UserHolder;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Autowired
	private PermissionFeign permissionFeign;

	@Autowired
	private JwtUtils jwtUtils;

	/**
	 * 用户注册
	 * @param user
	 */
	@Override
	@Transactional
	public Result register(User user) {
		save(user);
		permissionFeign.bindDefaultRole(user.getUserId());
		return Result.ok();
	}

	/**
	 * 用户登录
	 * @param loginDTO
	 */
	@Override
	public Result login(LoginDTO loginDTO) {
		String username = loginDTO.getUsername();
		String password = loginDTO.getPassword();

		User user = lambdaQuery().eq(User::getUsername, username).one();

		if(user == null) {
			return Result.error("用户不存在");
		}

		if(!password.equals(user.getPassword())) {
			return Result.error("密码错误");
		}

		String token = jwtUtils.createToken(user.getUserId());

		return Result.ok(token);
	}

	/**
	 * 获取用户列表
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@Override
	@Transactional
	public Result listUsers(Integer pageNo, Integer pageSize) {
		// 当前用户的id
		Long currentUserId = UserHolder.getUserId();
		// 查询当前用户身份id
		Long currentUserRoleId = permissionFeign.getUserRoleCode(currentUserId).getRoleId();

		// 如果是普通用户，直接返回自己的信息
		if(currentUserRoleId == 3L) {
			return Result.ok(getById(currentUserId));
		}

		// 分页参数
		Page<User> page = Page.of(pageNo, pageSize);
		Page<User> userPage = new Page<>();

		// 如果是超级管理员，查询所有用户
		if(currentUserRoleId == 1L) {
			userPage = page(page);
		}

		// 如果是管理员，调用permissionFeign查询普通用户id，在进行分页查询
		if(currentUserRoleId == 2L) {
			List<Long> userIds = permissionFeign.getUserRoleIds();
			if(userIds.isEmpty()) {
				return Result.ok(new ArrayList<>());
			}
			userPage = lambdaQuery().in(User::getUserId, userIds).page(page);
		}

		List<User> userList = userPage.getRecords();
		List<UserVo> userVoList = BeanUtil.copyToList(userList, UserVo.class);
		return Result.ok(userVoList);
	}

	/**
	 * 获取用户信息
	 * @param targetUserId
	 * @return
	 */
	@Override
	@Transactional
	public Result getUserInfo(Long targetUserId) {
		// 当前用户的id
		Long currenUserId = UserHolder.getUserId();

		// 查询需要查询的用户信息
		User targetUser = getById(targetUserId);

		if(targetUser == null) {
			return Result.error("用户不存在");
		}

		// 比较用户权限
		if(compareUser(currenUserId, targetUserId)) {
			return Result.ok(BeanUtil.copyProperties(targetUser, UserVo.class));
		}

		// 返回无权限
		return Result.error("无权限");
	}

	/**
	 * 修改用户信息
	 *
	 * @param userId
	 * @param userDto
	 * @return
	 */
	@Override
	public Result updateUserInfo(Long userId, UserDTO userDto) {
		// 当前用户的id
		Long currenUserId = UserHolder.getUserId();
		// 查询需要查询的用户信息
		User user = getById(userId);

		if(user == null) {
			return Result.error("用户不存在");
		}

		if(compareUser(currenUserId, userId)) {
			BeanUtils.copyProperties(userDto, user);
			updateById(user);
			return Result.ok("更改成功");
		}

		return Result.error("无权限");
	}

	/**
	 * 重置密码
	 * @param userId
	 * @return
	 */
	@Override
	public Result resetPassword(Long userId) {
		// 当前用户的id
		Long currentUserId = UserHolder.getUserId();

		if(!compareUser(currentUserId, userId)) {
			return Result.error("无权限");
		}

		boolean success = update().set("password", "123456").eq("user_id", userId).update();

		if(!success) {
			return Result.error("重置密码失败");
		}

		return Result.ok();
	}

	private boolean compareUser(Long currentUserId, Long targetUserId) {
		// 查询当前用户身份id
		Long currentUserRoleId = permissionFeign.getUserRoleCode(currentUserId).getRoleId();
		// 查询目标用户身份id
		Long targetUserRoleId = permissionFeign.getUserRoleCode(targetUserId).getRoleId();

		// 如果当前用户的id等于查询的用户id，则直接返回true
		if(Objects.equals(currentUserId, targetUserId)) {
			return true;
		}

		// 如果当前用户是超级管理员，返回true
		if(currentUserRoleId == 1L) {
			return true;
		}

		// 如果当前用户是管理员，并且需要查询的用户为普通用户，则返回true
		if(currentUserRoleId == 2L && targetUserRoleId == 3L) {
			return true;
		}

		// 如果都不是，返回false
		return false;
	}
}
